package com.wechat.android.app.ui.bottom;


import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.util.TypedValue;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.BounceInterpolator;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.easemob.cases.db.MessageDBHelper;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.model.EaseAtMessageHelper;
import com.hyphenate.easeui.ui.EaseConversationListFragment;
import com.hyphenate.easeui.widget.EaseConversationList;
import com.hyphenate.util.NetUtils;
import com.wechat.android.app.R;
import com.wechat.android.app.ui.ChatActivity;
import com.wechat.android.app.utils.PhoneUtils;
import com.wechat.android.app.widget.CustomFontEditText;
import com.wechat.android.app.widget.CustomFontTextView;

import libs.SwipeMenu;
import libs.SwipeMenuCreator;
import libs.SwipeMenuItem;



/**
 * Created by yang on 2017/11/23.
 * 消息
 */

public class MessageFragment extends EaseConversationListFragment {
    private CustomFontTextView errorText;
    private CustomFontTextView tvMessageEmpty;
    private SwipeMenuCreator creator;
    private final int SWIPE_MENU_ITEM_BUTTON_DELETE = 1;
    private View errorView = null;

    @Override
    protected void initView() {
        super.initView();
        errorView = (LinearLayout) View.inflate(getActivity(), R.layout.em_chat_neterror_item2, null);
        errorItemContainer.addView(errorView);
        View tipsView = (LinearLayout) View.inflate(getActivity(), R.layout.item_message_tips, null);
        conversationTipsContainer.addView(tipsView);
        tvMessageEmpty = (CustomFontTextView)tipsView.findViewById(R.id.tv_message_empty);
        tvMessageEmpty.setText("\uD81B\uDF2F\uD81B\uDF71\uD81B\uDF26\uD81B\uDFC4\uD81B\uDF04\uD81B\uDFD6\uD81B\uDF04\uD81B\uDFD4\uD81B\uDF33\uD81B\uDFD1");
        errorText = (CustomFontTextView) errorView.findViewById(R.id.tv_connect_errormsg);
        errorText.setText("\uD81B\uDF1E\uD81B\uDFA9\uD81B\uDF04\uD81B\uDF7B\uD81B\uDF2F\uD81B\uDF51\uD81B\uDF62\uD81B\uDF3D\uD81B\uDF54\uD81B\uDF16\uD81B\uDF60");

    }

    @Override
    protected void setUpView() {
        super.setUpView();
        // register context menu
        registerForContextMenu(conversationListView);
        titleBar.setVisibility(View.VISIBLE);
        titleBar.setTitle("\uD81B\uDF04\uD81B\uDFD4\uD81B\uDF16\uD81B\uDFC9");
        searchBar.setVisibility(View.GONE);

        creator = new SwipeMenuCreator() {

            @Override
            public void create(SwipeMenu menu) {

                SwipeMenuItem deleteItem = new SwipeMenuItem(getContext());
                deleteItem.setBackground(R.color.white);
                deleteItem.setWidth(dp2px(80));
                deleteItem.setTitleColor(Color.WHITE);
                deleteItem.setIcon(R.mipmap.icon_delete);
                deleteItem.setId(SWIPE_MENU_ITEM_BUTTON_DELETE);
                menu.addRightMenuItem(deleteItem);
            }
        };
        conversationListView.setMenuCreator(creator);
        conversationListView.setOpenInterpolator(new BounceInterpolator());
        conversationListView.setCloseInterpolator(new BounceInterpolator());

        conversationListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                EMConversation conversation = conversationListView.getItem(position);
                String username = conversation.conversationId();
                if (username.equals(EMClient.getInstance().getCurrentUser()))
                    PhoneUtils.ShowToastMessage(getActivity(), getString(R.string.Cant_chat_with_yourself));
                else {
                    // start chat acitivity
                    Intent intent = new Intent(getActivity(), ChatActivity.class);
                    if (conversation.isGroup()) {
                        if (conversation.getType() == EMConversation.EMConversationType.ChatRoom) {
                            // it's group chat
                            //intent.putExtra(Constants.EXTRA_CHAT_TYPE, Constants.CHATTYPE_CHATROOM);
                        } else {
                            intent.putExtra(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_GROUP);
                        }

                    }
                    // it's single chat
                    intent.putExtra(EaseConstant.EXTRA_USER_ID, username);
                    startActivity(intent);
                }
            }
        });
        conversationListView.setOnMenuItemClickListener(new EaseConversationList.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(int position, boolean isRightMenu, SwipeMenu menu, SwipeMenuItem item) {
                EMConversation conversation = conversationListView.getItem(position);
                switch (item.getId()) {
                    case SWIPE_MENU_ITEM_BUTTON_DELETE:
                        if (conversation.getType() == EMConversation.EMConversationType.GroupChat) {
                            EaseAtMessageHelper.get().removeAtMeGroup(conversation.conversationId());
                        }
                        try {
                            // delete conversation
                            EMClient.getInstance().chatManager().deleteConversation(conversation.conversationId(), false);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                }
                refresh();
                return false;
            }
        });
        //red packet code : 红包回执消息在会话列表最后一条消息的展示
        conversationListView.setConversationListHelper(new EaseConversationList.EaseConversationListHelper() {
            @Override
            public String onSetItemSecondaryText(EMMessage lastMessage) {
                /*if (lastMessage.getBooleanAttribute(RedPacketConstant.MESSAGE_ATTR_IS_RED_PACKET_ACK_MESSAGE, false)) {
                    String sendNick = lastMessage.getStringAttribute(RedPacketConstant.EXTRA_RED_PACKET_SENDER_NAME, "");
                    String receiveNick = lastMessage.getStringAttribute(RedPacketConstant.EXTRA_RED_PACKET_RECEIVER_NAME, "");
                    String msg;
                    if (lastMessage.direct() == EMMessage.Direct.RECEIVE) {
                        msg = String.format(getResources().getString(R.string.msg_someone_take_red_packet), receiveNick);
                    } else {
                        if (sendNick.equals(receiveNick)) {
                            msg = getResources().getString(R.string.msg_take_red_packet);
                        } else {
                            msg = String.format(getResources().getString(R.string.msg_take_someone_red_packet), sendNick);
                        }
                    }
                    return msg;
                }*/
                return null;
            }
        });
        //super.setUpView();
        //end of red packet code
        //setListMarginBottom();
    }

    @Override
    protected void onConnectionDisconnected() {
        super.onConnectionDisconnected();
        if (NetUtils.hasNetwork(getActivity())) {
            errorText.setText("\uD81B\uDF1E\uD81B\uDFA9\uD81B\uDF04\uD81B\uDF7B\uD81B\uDF2F\uD81B\uDF51\uD81B\uDF62\uD81B\uDF3D\uD81B\uDF54\uD81B\uDF16\uD81B\uDF60");
        } else {
            errorText.setText("\uD81B\uDF1E\uD81B\uDFA9\uD81B\uDF04\uD81B\uDF7B\uD81B\uDF2F\uD81B\uDF51\uD81B\uDF62\uD81B\uDF3D\uD81B\uDF54\uD81B\uDF16\uD81B\uDF60");
        }

    }


    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        getActivity().getMenuInflater().inflate(R.menu.em_delete_message, menu);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        boolean deleteMessage = false;
        if (item.getItemId() == R.id.delete_message) {
            deleteMessage = true;
        } else if (item.getItemId() == R.id.delete_conversation) {
            deleteMessage = false;
        }
        EMConversation tobeDeleteCons = conversationListView.getItem(((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).position);
        if (tobeDeleteCons == null) {
            return true;
        }
        if (tobeDeleteCons.getType() == EMConversation.EMConversationType.GroupChat) {
            EaseAtMessageHelper.get().removeAtMeGroup(tobeDeleteCons.conversationId());
        }
        try {
            // delete conversation
            EMClient.getInstance().chatManager().deleteConversation(tobeDeleteCons.conversationId(), deleteMessage);
            MessageDBHelper.getInstance().deleteMessage(tobeDeleteCons.conversationId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        refresh();

        //TODO update unread count
        //((MainActivity) getActivity()).updateUnreadLabel();
        return true;
    }


    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                getResources().getDisplayMetrics());
    }


    //TODO 网络切换

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
